package com.tutucms.service.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wangxudong on 2020/05/11.
 *
 * @version: 1.0
 * @modified :
 */
@Slf4j
public class SensitiveWordFilterUtil {

    private static Pattern pattern = null;

    static {
        StringBuffer patternBuffer = new StringBuffer();
        try {
            InputStream in = SensitiveWordFilterUtil.class.getClassLoader().getResourceAsStream("sensitive.dict");
            Properties property = new Properties();
            property.load(in);
            Enumeration<?> enu = property.propertyNames();
            patternBuffer.append("(");
            while (enu.hasMoreElements()) {
                String content = (String) enu.nextElement();
                patternBuffer.append(content + "|");
            }
            patternBuffer.deleteCharAt(patternBuffer.length() - 1);
            patternBuffer.append(")");
            //System.out.println(patternBuffer);
            // unix换成UTF-8
            // pattern = Pattern.compile(new
            // String(patternBuf.toString().getBytes("ISO-8859-1"), "UTF-8"));
            // win下换成gb2312
            // pattern = Pattern.compile(new String(patternBuf.toString()
            // .getBytes("ISO-8859-1"), "gb2312"));
            // 装换编码
            pattern = Pattern.compile(patternBuffer.toString());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    public static String doFilter(String str) {
        Matcher m = pattern.matcher(str);
//      while (m.find()) {
//          System.out.println("The result is here :" + m.group());
//      }
        // 选择替换方式，这里以* 号代替
        str = m.replaceAll("*");
        return str;
    }

}
